package com.hhxy.login.servlet;

import com.hhxy.login.pojo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * @author ghp
 * @date 2022/9/26
 * @Title
 * @description
 */
@WebServlet("/indexServlet")
public class IndexServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 解决乱码问题
        response.setContentType("text/html;charset=utf-8");
        // 创建或者获取保存用户信息的Session对象
        HttpSession session = request.getSession();
        //从Session域中获取user
        User user = (User) session.getAttribute("user");
        if (user == null) {
            //如果user为null，说明还没有登录
            response.getWriter().print(
                    "您还没有登录，请<a href='http://localhost:8080/day04_Fifth/html/login.html'>登录</a>");
        } else {
            //如果user不为null，说明已经登录成功了
            response.getWriter().write("您已登录，欢迎您，"+user.getUsername()+"!");
            response.getWriter().write("<a href='/day04_Fifth/logoutServlet'>退出</a>");
            //创建Cookie，并存放Session的id，将它发送到客户端
            Cookie cookie = new Cookie("JSESSIONID",session.getId());
            cookie.setMaxAge(60*3);
            cookie.setPath("/day04_Fifth");
            response.addCookie(cookie);
        }
    }
}